<template>
  <div class="login">
    <el-form
      class="login-form"
      label-position="top"
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          class="login-btn"
          type="primary"
          @click="onSubmit"
          :loading="isLoginLoading"
        >
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { login } from '@/services/user'
import { Form } from 'element-ui'

export default Vue.extend({
  name: 'LoginIndex',
  data() {
    return {
      isLoginLoading: false,
      form: {
        // phone: '18201288771',
        phone: '18211111111',
        password: '111111'
      },
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1\d{10}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在6到18个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async onSubmit() {
      try {
        // 1.表单验证
        await (this.$refs.form as Form).validate()
        // 2.验证通过 ——> 提交表单
        this.isLoginLoading = true
        const { data } = await login(this.form)
        console.log(data)
        // 3.处理请求结果
        if (data.state != 1) {
          // 失败：给出提示
          this.$message.error(data.message)
        } else {
          this.$store.commit('setUser', data.content)
          // 成功：跳转到首页
          this.$router.push({
            path: (this.$route.query.redirect as string) || '/'
          })
          // this.$router.push({
          //   name: 'home'
          // })
          this.$message.success('登录成功')
        }
        this.isLoginLoading = false
      } catch (err) {
        console.log('登录失败', err)
      }
    }
  }
})
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  .login-form {
    width: 300px;
    padding: 20px;
    background: #fff;
    border-radius: 5px;
    .login-btn {
      width: 100%;
    }
  }
}
</style>
